package com.ym.jiujiangeyou.fragment;

import java.io.IOException;
import java.io.Serializable;

import java.util.HashMap;

import org.ksoap2.serialization.SoapObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ym.jiujiangeyou.R;
import com.ym.jiujiangeyou.entity.SimpleWeather;
import com.ym.jiujiangeyou.entity.Weather;
import com.ym.jiujiangeyou.parse.WeatherParse;
import com.ym.jiujiangeyou.ui.DialogView;
import com.ym.jiujiangeyou.util.ACache;
import com.ym.jiujiangeyou.util.ConfigCache;
import com.ym.jiujiangeyou.util.Constants;
import com.ym.jiujiangeyou.util.NetworkUtil;
import com.ym.jiujiangeyou.util.Util;
import com.ym.jiujiangeyou.werther.WeatherReader;
import com.ym.jiujiangeyou.werther.WebServiceUtils;
import com.ym.jiujiangeyou.werther.WebServiceUtils;
import com.ym.jiujiangeyou.werther.WebServiceUtils.WebServiceCallBack;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 叶铭
 * @email yeming_1001@163.com
 * @version V1.0
 */
public class WeatherFragment extends Fragment implements OnClickListener {

	private TextView title_text, time_text, // 时间
			city, week_today, // 星期
			humidity, // 湿度
			wind, // 风力
			temperature, // 实时温度
			climate; // 天气
	private TextView week1, week2, week3, // 明后几天的星期
			temperature1, temperature2, temperature3, // 温度
			climate1, climate2, climate3, // 天气
			wind1, wind2, wind3; // 风力
	private ImageView weather_img1, weather_img2, weather_img3; // 明后几天的天气icon
	private ImageView weather_image; // 天气icon
	private ImageView updateBtn; // 更新按钮
	private SimpleWeather simpleWeather;
	private Weather weather;
	private ProgressBar updateProgressBar;
	Toast toast;
	// private ACache cache ;

	private static final int GET_FAIL = 4; // 读取失败
	private static final int NET_ERROR = 5; // 网络出错
	private static final int GET_CACHE_WEATHER = 6 ;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Constants.REFRESH_WEATHER_RESULT:
				
				break;
			case GET_CACHE_WEATHER:
				getCacheWeather() ;
				break ;
			case Constants.UPDATE_EXISTS_CITY:
				updateWeather();
				break;
			case Constants.GET_WEATHER_RESULT:
				updateWeatherInfo();
				updateBtn.setVisibility(View.VISIBLE);
				updateProgressBar.setVisibility(View.GONE);
				// updateOtherWeather(weatherinfo) ;
				toast = DialogView.popToast(getActivity(),
						R.string.update_success);
				toast.show();
				break;
			case NET_ERROR:
				updateBtn.setVisibility(View.VISIBLE);
				updateProgressBar.setVisibility(View.GONE);
				/*toast = DialogView
						.popToast(getActivity(), R.string.update_fail);
				toast.show();*/
				break;
			case GET_FAIL:
				updateBtn.setVisibility(View.VISIBLE);
				updateProgressBar.setVisibility(View.GONE);
				/*toast = DialogView
						.popToast(getActivity(), R.string.update_fail);
				toast.show();*/
				
				 Toast.makeText(getActivity(), R.string.fail_to_get_weather,
				 Toast.LENGTH_SHORT) .show();
				 
				break;
			default:
				break;
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 不转换没有 @Expose 注解的字段
		/*
		 * gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
		 * .create();
		 */
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.weather, null, false);
		initResouce(view);
		// cache = ACache.get(getActivity()) ; // 初始化缓存管理
		return view;

	}

	public void initResouce(View view) {

		// View view_content = view.findViewById(R.id.weather_today) ;
		weather = null;
		simpleWeather = null;
		title_text = (TextView) view.findViewById(R.id.title_text);
		title_text.setText(R.string.title_text_weather);
		updateProgressBar = (ProgressBar) view
				.findViewById(R.id.title_update_progress);
		updateBtn = (ImageView) view.findViewById(R.id.title_update_btn);
		updateBtn.setOnClickListener(this);
		time_text = (TextView) view.findViewById(R.id.time);
		city = (TextView) view.findViewById(R.id.city);
		week_today = (TextView) view.findViewById(R.id.week_today);
		week_today.setText("今天 " + Util.getWeek(0, Util.XING_QI));
		humidity = (TextView) view.findViewById(R.id.humidity);
		wind = (TextView) view.findViewById(R.id.wind);
		temperature = (TextView) view.findViewById(R.id.temp);
		climate = (TextView) view.findViewById(R.id.climate);
		weather_image = (ImageView) view.findViewById(R.id.weather_img);

		View other_content = view.findViewById(R.id.weather_other);

		View view1 = other_content.findViewById(R.id.subitem1);
		View view2 = other_content.findViewById(R.id.subitem2);
		View view3 = other_content.findViewById(R.id.subitem3);

		week1 = (TextView) view1.findViewById(R.id.week);
		week2 = (TextView) view2.findViewById(R.id.week);
		week3 = (TextView) view3.findViewById(R.id.week);

		week1.setText(Util.getWeek(1, Util.XING_QI));
		week2.setText(Util.getWeek(2, Util.XING_QI));
		week3.setText(Util.getWeek(3, Util.XING_QI));

		temperature1 = (TextView) view1.findViewById(R.id.temperature);
		temperature2 = (TextView) view2.findViewById(R.id.temperature);
		temperature3 = (TextView) view3.findViewById(R.id.temperature);

		wind1 = (TextView) view1.findViewById(R.id.wind);
		wind2 = (TextView) view2.findViewById(R.id.wind);
		wind3 = (TextView) view3.findViewById(R.id.wind);

		climate1 = (TextView) view1.findViewById(R.id.climate);
		climate2 = (TextView) view2.findViewById(R.id.climate);
		climate3 = (TextView) view3.findViewById(R.id.climate);

		weather_img1 = (ImageView) view1.findViewById(R.id.weather_img);
		weather_img2 = (ImageView) view2.findViewById(R.id.weather_img);
		weather_img3 = (ImageView) view3.findViewById(R.id.weather_img);

		if(ConfigCache.isExitCacheFile(Constants.WEATHER_FILE_CACHE) && ConfigCache.isExitCacheFile(Constants.SIMPLEWEATHER_FILE_CACHE)){
			handler.sendEmptyMessage(GET_CACHE_WEATHER);
		}else{
			handler.sendEmptyMessage(Constants.UPDATE_EXISTS_CITY) ;
		}
		

	}
	
	/** 
	*   
	* @retur  void 
	* @Description: 获取缓存天气信息 
	*/
	public void getCacheWeather(){
		time_text.setText(R.string.isupdateing);
		updateBtn.setVisibility(View.GONE);
		updateProgressBar.setVisibility(View.VISIBLE);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String wstr = ConfigCache.getUrlCache(Constants.WEATHER_FILE_CACHE) ;
				String simstr = ConfigCache.getUrlCache(Constants.SIMPLEWEATHER_FILE_CACHE) ;
				//Log.d("System.out", "----------1-----------"+wstr) ;
				if(wstr != null && simstr != null){
					//Log.d("System.out", "----------1234-----------"+weather.toString()) ;
					weather = WeatherParse.getWeatherFormJson(wstr) ;
					simpleWeather = WeatherParse.getSimpleWeatherFormJson(simstr) ;
				//	Log.d("System.out", "----------2-----------"+weather.toString()) ;
				//	Log.d("System.out", "----------3-----------"+simpleWeather.toString()) ;
					if(simpleWeather != null && weather != null){
					//	Log.d("System.out", "----------4-----------") ;
						handler.sendEmptyMessage(Constants.GET_WEATHER_RESULT);
					//	Log.d("System.out", "----------5-----------") ;
					}
				}
			}
		}).start() ;
	}

	// 获取weather信息
	private void updateWeather() {
		if (!NetworkUtil.isNetworkAvailable(getActivity())) {
			// Toast.makeText(getActivity(), "网络不好哦！", 0).show() ;
			//return;
		}
		time_text.setText(R.string.isupdateing);
		updateBtn.setVisibility(View.GONE);
		updateProgressBar.setVisibility(View.VISIBLE);
		
		/*String wstr = ConfigCache.getUrlCache(Constants.WEATHER_FILE_CACHE) ;
		String simstr = ConfigCache.getUrlCache(Constants.SIMPLEWEATHER_FILE_CACHE) ;
		if(wstr){
			
		}*/
		/*try {
			getCacheWeather() ;
			Log.d("System.out", "----------1-----------") ;
			if(simpleWeather != null && weather != null){
				Log.d("System.out", "----------4-----------") ;
				handler.sendEmptyMessage(Constants.GET_WEATHER_RESULT);
				Log.d("System.out", "----------5-----------") ;
				return ;
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			handler.sendEmptyMessage(GET_FAIL);
		}*/
	//	Log.d("System.out", "----------1223-----------") ;
		final HashMap<String, String> properties = new HashMap<String, String>();
		properties.put("theCityCode", "九江");
		// 启动线程获取天气信息
		WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL,
				"getWeather", properties, new WebServiceCallBack() {

					@Override
					public void callBack(SoapObject result) {
						// TODO Auto-generated method stub
						if (result != null) {
							SoapObject detail = (SoapObject) result
									.getProperty("getWeatherResult");
							try {
								parseWeather(detail);
								// cache.put("weather", (Serializable)detail) ;
								// cache.put("weather", detail) ;
								// cache.put("weather", detail.toString()) ;
								if (simpleWeather != null && weather != null) {
									ConfigCache.setUrlCache(WeatherParse.WeatherToJson(weather), Constants.WEATHER_FILE_CACHE) ;
									ConfigCache.setUrlCache(WeatherParse.SimpleWeatherToJson(simpleWeather), Constants.SIMPLEWEATHER_FILE_CACHE) ;
									handler.sendEmptyMessage(Constants.GET_WEATHER_RESULT);
								}
							} catch (Exception e) {
								// TODO Auto-generated catch block
								Toast.makeText(
										WeatherFragment.this.getActivity(),
										R.string.get_webservice_error,
										Toast.LENGTH_SHORT).show();
								handler.sendEmptyMessage(NET_ERROR);
								e.printStackTrace();
							}

						} else {
							Toast.makeText(WeatherFragment.this.getActivity(),
									R.string.get_webservice_error,
									Toast.LENGTH_SHORT).show();
							handler.sendEmptyMessage(NET_ERROR);
						}
					}
				});

		// }

		// }.start();

	}

	/**
	 * 更新天气界面
	 */
	private void updateWeatherInfo() {

		try {
			if (weather != null) {
				city.setText(weather.getCity());
				String windstr = weather.getWind();
				wind.setText(windstr);
				String climatestr = weather.getClimate();
				climate.setText(getClimate(climatestr.split(" ")[1]));
				// 设置 天气icon
				// int resid = getWeatherIcon(climatestr);
				// weather_image.setImageResource(parseIcon(weather.getWeather_img()));
				weather_image.setImageResource(getWeatherIcon(climatestr
						.split(" ")[1]));
				temperature.setText(weather.getTemperature());
				humidity.setText(weather.getHumidity());
				// System.out.println("---------" +
				// simpleWeatherinfo.getTemp());
				time_text.setText(Util.getDay_m() + " "
						+ weather.getTime().split(" ")[1]);
				if (simpleWeather != null) {
					updateOtherWeather(simpleWeather);
				}

			} else {
				time_text.setText(Util.getDay_m());
				temperature.setText("N/A");
				wind.setText("N/A");
				climate.setText("N/A");
				weather_image.setImageResource(R.drawable.a_0);
				Toast.makeText(getActivity(), R.string.fail_to_get_weather, 0)
						.show();
			}
		} catch (Exception e) {
			Toast.makeText(getActivity(), R.string.fail_to_get_weather, 0)
					.show();
		}
	}

	// 更新 明后几天的天气信息
	public void updateOtherWeather(SimpleWeather simpleWeather) {
		if (simpleWeather != null) {

			weather_img1.setImageResource(getWeatherIcon(simpleWeather
					.getClimate1().split(" ")[1]));
			weather_img2.setImageResource(getWeatherIcon(simpleWeather
					.getClimate2().split(" ")[1]));
			weather_img3.setImageResource(getWeatherIcon(simpleWeather
					.getClimate3().split(" ")[1]));

			climate1.setText(getClimate(simpleWeather.getClimate1().split(" ")[1]));
			climate2.setText(getClimate(simpleWeather.getClimate2().split(" ")[1]));
			climate3.setText(getClimate(simpleWeather.getClimate3().split(" ")[1]));

			temperature1.setText(temperatureReplace(simpleWeather
					.getTemperature1()));
			temperature2.setText(temperatureReplace(simpleWeather
					.getTemperature2()));
			temperature3.setText(temperatureReplace(simpleWeather
					.getTemperature3()));

			wind1.setText(getSimpleWeatherWind(simpleWeather.getWind1()));
			wind2.setText(getSimpleWeatherWind(simpleWeather.getWind2()));
			wind3.setText(getSimpleWeatherWind(simpleWeather.getWind3()));
		} else {
			weather_img1.setImageResource(R.drawable.a_0);
			weather_img2.setImageResource(R.drawable.a_0);
			weather_img3.setImageResource(R.drawable.a_0);

			climate1.setText("N/A");
			climate2.setText("N/A");
			climate3.setText("N/A");

			temperature1.setText("N/A");
			temperature2.setText("N/A");
			temperature3.setText("N/A");

			wind1.setText("N/A");
			wind2.setText("N/A");
			wind3.setText("N/A");
			Toast.makeText(getActivity(), R.string.fail_to_get_weather, 0)
					.show();
		}
	}

	/**
	 * @param climate
	 * @return
	 * @retur String
	 * @Description: 转换天气
	 */
	public String getClimate(String climate) {
		String clim = "晴";
		if (climate.contains("转")) {
			String[] strs = climate.split("转");
			climate = strs[0];
		}
		clim = climate;
		return clim;

	}

	/**
	 * @param climate
	 * @return
	 * @retur String
	 * @Description: 获取匹配的Wind
	 */
	public String getSimpleWeatherWind(String wind) {
		String sWind = "";
		if (TextUtils.isEmpty(wind))
			return "N/A";
		String[] strs = { "晴", "晴" };
		if (wind.contains("转")) {// 天气带转字，取前面那部分
			strs = wind.split("转");
			wind = strs[0];
		}
		if (wind.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
			strs = wind.split("到");
			wind = strs[1];
		}
		sWind = wind;
		return sWind;
	}

	/**
	 * @param climate
	 * @return
	 * @retur int
	 * @Description: 匹配ICON
	 */
	public int getWeatherIcon(String climate) {
		int weatherRes = R.drawable.a_0;
		if (TextUtils.isEmpty(climate))
			return weatherRes;
		String[] strs = { "晴", "晴" };
		if (climate.contains("转")) {// 天气带转字，取前面那部分
			strs = climate.split("转");
			climate = strs[0];
		}
		if (climate.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
			strs = climate.split("到");
			climate = strs[1];
		}
		// System.out.println("----处理后的天气-----" + climate);
		weatherRes = parseIcon(climate);
		return weatherRes;
	}

	// 工具方法，该方法负责把返回的天气图标字符串，转换为程序的图片资源ID。
	private int parseIcon(String strweather) {
		if (strweather == null)
			return R.drawable.a_0;
		if ("晴".equals(strweather))
			return R.drawable.a_0;
		if ("多云".equals(strweather))
			return R.drawable.a_1;
		if ("阴".equals(strweather))
			return R.drawable.a_2;
		if ("阵雨".equals(strweather))
			return R.drawable.a_3;
		if ("雷阵雨".equals(strweather))
			return R.drawable.a_4;
		if ("雷阵雨冰雹".equals(strweather))
			return R.drawable.a_5;
		if ("雨夹雪".equals(strweather))
			return R.drawable.a_6;
		if ("小雨".equals(strweather))
			return R.drawable.a_7;
		if ("中雨".equals(strweather))
			return R.drawable.a_8;
		if ("大雨".equals(strweather))
			return R.drawable.a_9;
		if ("暴雨".equals(strweather))
			return R.drawable.a_10;
		if ("大暴雨".equals(strweather))
			return R.drawable.a_11;
		if ("特大暴雨".equals(strweather))
			return R.drawable.a_12;
		if ("阵雪".equals(strweather))
			return R.drawable.a_13;
		if ("小雪".equals(strweather))
			return R.drawable.a_14;
		if ("中雪".equals(strweather))
			return R.drawable.a_15;
		if ("大雪".equals(strweather))
			return R.drawable.a_16;
		if ("暴雪".equals(strweather))
			return R.drawable.a_17;
		if ("雾".equals(strweather))
			return R.drawable.a_18;
		if ("冻雨".equals(strweather))
			return R.drawable.a_19;
		if ("沙尘暴".equals(strweather))
			return R.drawable.a_20;
		if ("浮尘".equals(strweather))
			return R.drawable.a_29;
		if ("扬沙".equals(strweather))
			return R.drawable.a_30;
		if ("强沙尘暴".equals(strweather))
			return R.drawable.a_31;
		return 0;
	}

	/*
	 * private int parseIcon(String strweather) { if (strweather == null) return
	 * R.drawable.a_0; if ("0.gif".equals(strweather)) return R.drawable.a_0; if
	 * ("1.gif".equals(strweather)) return R.drawable.a_1; if
	 * ("2.gif".equals(strweather)) return R.drawable.a_2; if
	 * ("3.gif".equals(strweather)) return R.drawable.a_3; if
	 * ("4.gif".equals(strweather)) return R.drawable.a_4; if
	 * ("5.gif".equals(strweather)) return R.drawable.a_5; if
	 * ("6.gif".equals(strweather)) return R.drawable.a_6; if
	 * ("7.gif".equals(strweather)) return R.drawable.a_7; if
	 * ("8.gif".equals(strweather)) return R.drawable.a_8; if
	 * ("9.gif".equals(strweather)) return R.drawable.a_9; if
	 * ("10.gif".equals(strweather)) return R.drawable.a_10; if
	 * ("11.gif".equals(strweather)) return R.drawable.a_11; if
	 * ("12.gif".equals(strweather)) return R.drawable.a_12; if
	 * ("13.gif".equals(strweather)) return R.drawable.a_13; if
	 * ("14.gif".equals(strweather)) return R.drawable.a_14; if
	 * ("15.gif".equals(strweather)) return R.drawable.a_15; if
	 * ("16.gif".equals(strweather)) return R.drawable.a_16; if
	 * ("17.gif".equals(strweather)) return R.drawable.a_17; if
	 * ("18.gif".equals(strweather)) return R.drawable.a_18; if
	 * ("19.gif".equals(strweather)) return R.drawable.a_19; if
	 * ("20.gif".equals(strweather)) return R.drawable.a_20; if
	 * ("29.gif".equals(strweather)) return R.drawable.a_29; if
	 * ("30.gif".equals(strweather)) return R.drawable.a_30; if
	 * ("31.gif".equals(strweather)) return R.drawable.a_31; return 0; }
	 */

	// 更新weather信息
	private void refreshWeather() {
		if (!NetworkUtil.isNetworkAvailable(getActivity())) {
			// Toast.makeText(getActivity(), "网络不好哦！", 0).show() ;
			return;
		}
		time_text.setText(R.string.isupdateing);
		updateBtn.setVisibility(View.GONE);
		updateProgressBar.setVisibility(View.VISIBLE);
		final HashMap<String, String> properties = new HashMap<String, String>();
		properties.put("theCityCode", "九江");
		// 启动线程获取天气信息
		WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL,
				"getWeather", properties, new WebServiceCallBack() {

					@SuppressWarnings("unused")
					@Override
					public void callBack(SoapObject result) {
						// TODO Auto-generated method stub
						if (result != null) {
							SoapObject detail = (SoapObject) result
									.getProperty("getWeatherResult");
							Log.d("System.out",
									"------------" + detail.toString());
							try {
								parseWeather(detail);
								if (simpleWeather != null && weather != null) {
									ConfigCache.setUrlCache(WeatherParse.WeatherToJson(weather), Constants.WEATHER_FILE_CACHE) ;
									ConfigCache.setUrlCache(WeatherParse.SimpleWeatherToJson(simpleWeather), Constants.SIMPLEWEATHER_FILE_CACHE) ;
									handler.sendEmptyMessage(Constants.GET_WEATHER_RESULT);
								}
							} catch (Exception e) {
								// TODO Auto-generated catch block
								Toast.makeText(
										WeatherFragment.this.getActivity(),
										R.string.get_webservice_error,
										Toast.LENGTH_SHORT).show();
								handler.sendEmptyMessage(NET_ERROR);
								e.printStackTrace();
							}

						} else {
							Toast.makeText(WeatherFragment.this.getActivity(),
									R.string.get_webservice_error,
									Toast.LENGTH_SHORT).show();
							handler.sendEmptyMessage(NET_ERROR);
						}
					}
				});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_update_btn:
			refreshWeather();
			break;

		default:
			break;
		}
	}

	/**
	 * @param str
	 * @return
	 * @retur String
	 * @Description: 温度 / 转换成 ~
	 */
	public String temperatureReplace(String str) {
		String tem = str;
		if (str.contains("/")) {
			tem = str.replace("/", "~");
		}
		return tem;
	}

	/**
	 * @param detail
	 * @retur void
	 * @Description: 解析数据 初始化 天气 对象
	 */
	public void parseWeather(SoapObject detail) {
		String str = detail.getProperty(4).toString();
		weather = new Weather(detail.getProperty(3).toString(), detail
				.getProperty(1).toString(), str.split("；")[2],
				str.split("；")[1].split("：")[1],
				str.split("；")[0].split("：")[2], detail.getProperty(7)
						.toString(), detail.getProperty(10).toString());
		simpleWeather = new SimpleWeather(detail.getProperty(13).toString(),
				detail.getProperty(18).toString(), detail.getProperty(23)
						.toString(), detail.getProperty(12).toString(), detail
						.getProperty(17).toString(), detail.getProperty(22)
						.toString(), detail.getProperty(14).toString(), detail
						.getProperty(19).toString(), detail.getProperty(24)
						.toString(), detail.getProperty(15).toString(), detail
						.getProperty(20).toString(), detail.getProperty(26)
						.toString());

	}

}
